package services;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;

import ApplicationLogic.controllers.SearchController;

@Path("/search")
public class SEARCHServiceFacade extends AbstractService
{
	@GET
	@Produces(MediaType.TEXT_XML)
	public String SearchWithCriteria(@Context UriInfo allUri ) throws Exception 
	{ 
	    
		MultivaluedMap<String, String> mpAllQueParams = allUri.getQueryParameters(); 
		String returnedModels = "";
	    
		SearchController SC = new SearchController();
	  	try 
	    {
	    	boolean SearchingForChildModel = false;
	    	//We get the parameters
	    	String Model = mpAllQueParams.getFirst("model");
			String ParentModel = mpAllQueParams.getFirst("ParentModel");
			String ParentChildAttribute = mpAllQueParams.getFirst("ParentChildAttribute");
			String ParentModelID = mpAllQueParams.getFirst("ParentModelID");
			int PageNumber = Integer.parseInt(mpAllQueParams.getFirst("Page"));
			mpAllQueParams.remove("model");
			mpAllQueParams.remove("Page");
			mpAllQueParams.remove("ParentModel");
			mpAllQueParams.remove("ParentModelID");
			mpAllQueParams.remove("ParentChildAttribute");
	    	
			if(ParentModel != null && ParentChildAttribute != null && ParentModelID !=null)
				SearchingForChildModel = true;
	    	 
	    	
	    	if (SearchingForChildModel)
	    		returnedModels = SC.SearchForChildModelByURI(Model,ParentModel,ParentChildAttribute,ParentModelID,PageNumber,mpAllQueParams);
	    	else 
	    		returnedModels = SC.SearchForModelByURI(Model, PageNumber, mpAllQueParams);
			
	    } 
	    catch (NumberFormatException nfe) //If the Page param failed to be converted into int,
	    {
	    	ReturnException("The Page parameter in the URI must be a number");
	    }
	    catch (Exception e) 
	    {
	    	ReturnException(e.getMessage());
	   	}
	
	  	return returnedModels;
	} 

	@GET
	@Produces(MediaType.TEXT_XML)
	@Path("getmodelsnames")
	public String SearchAllModelNames()
	{
		 SearchController SC = new SearchController();
		 String Names = "";
		 try
		 {
			 Names = SC.SearchForAllModelNames();
			 
		 }
		 catch(Exception e)
		 {
			 ReturnException(e.getMessage());
		 }
		 
		 return Names;
	}
	
	@GET
	@Produces(MediaType.TEXT_XML)
	@Path("getemptymodel")
	public String SearchEmptyModel(@QueryParam("model") String model)
	{
		String SerializedEmptyModel = "";
		try
		{
		SearchController SC = new SearchController();
		SerializedEmptyModel = SC.SearchForAnEmptyModel(model);
		
		
		}
		catch(Exception e)
		{
			 ReturnException(e.getMessage());
		}
	
		return SerializedEmptyModel;
	}


}
